import * as vscode from 'vscode';
import * as fs from 'fs';
import QuickAccessTreeProvider from './views/quick-access-tree';
import DSHome from './home';
import RemoteContainer, { openProjectWithoutLogging } from './remote-container';
import User from './user';
import DevstarAPIHandler from './devstar-api';
import * as os from 'os';
import * as utils from './utils';

export class DevStarExtension {
  user: User;
  remoteContainer: RemoteContainer;
  dsHome: DSHome;

  constructor(private context: vscode.ExtensionContext) {
    this.user = new User(context);
    // 只保持一个User实例
    this.remoteContainer = new RemoteContainer(this.user);
    this.dsHome = new DSHome(context, this.user);

    // 确定local系统是否为win，如果是，保存powershell版本
    if (vscode.env.remoteName === undefined) {
      if (os.platform() === 'win32') {
        utils.powershellVersion()
          .then(powershellVersion => {
            this.context.globalState.update('powershellVersion', powershellVersion)
          })
      }
    }

    // support for open with vscode in web
    const handler = vscode.window.registerUriHandler({
      handleUri: async (uri: vscode.Uri) => {
        const devstarAPIHandler = new DevstarAPIHandler()

        if (uri.path === '/openProject') {
          const params = new URLSearchParams(uri.query);
          const host = params.get('host');
          const hostname = params.get('hostname');
          const port = params.get('port');
          const username = params.get('username');
          const path = params.get('path');
          const access_token = params.get('access_token');
          const devstar_username = params.get('devstar_username');

          if (host && hostname && port && username && path) {
            const container_host = host;
            const container_hostname = hostname
            const container_port = parseInt(port, 10);
            const container_username = username;
            const project_path = decodeURIComponent(path);

            if (access_token && devstar_username) {
              if (!this.user.isLogged()) {
                // 如果没有用户登录，则直接登录;
                const res = await this.user.login(access_token, devstar_username)
                if (res === 'ok') {
                  await this.remoteContainer.firstOpenProject(container_host, container_hostname, container_port, container_username, project_path, this.context)
                }
              } else if (devstar_username === this.user.getUsernameFromLocal()) {
                // 如果同用户已经登录，则忽略，直接打开项目
                await this.remoteContainer.firstOpenProject(container_host, container_hostname, container_port, container_username, project_path, this.context)
              } else {
                // 如果不是同用户，可以选择切换用户，或者不切换登录用户，直接打开容器
                const selection = await vscode.window.showWarningMessage(`已登录用户：${this.user.getUsernameFromLocal()}，是否切换用户？`,
                  'Yes', 'No',);
                if (selection === 'Yes') {
                  // 如果没有用户登录，则直接登录;
                  const res = await this.user.login(access_token, devstar_username)
                  if (res === 'ok') {
                    await this.remoteContainer.firstOpenProject(container_host, container_hostname, container_port, container_username, project_path, this.context)
                  }
                } else if (selection === 'No') {
                  await openProjectWithoutLogging(container_host, container_port, container_username, project_path);
                }
              }
            } else {
              await openProjectWithoutLogging(container_host, container_port, container_username, project_path);
            }
          } else {
            vscode.window.showErrorMessage('Missing required parameters.');
          }
        } else if (uri.path === "/openProjectSkippingLoginCheck") {
          // 仅有已登录、不用改变登录状态时，用此流程
          const params = new URLSearchParams(uri.query);
          const host = params.get('host');
          const hostname = params.get('hostname');
          const port = params.get('port');
          const username = params.get('username');
          const path = params.get('path');

          if (host && hostname && port && username && path) {
            const container_host = host;
            const container_hostname = hostname
            const container_port = parseInt(port, 10);
            const container_username = username;
            const project_path = decodeURIComponent(path);

            await this.remoteContainer.firstOpenProject(container_host, container_hostname, container_port, container_username, project_path, this.context)
          }
        }
      }
    });

    context.subscriptions.push(handler);

    context.subscriptions.push(
      vscode.window.registerTreeDataProvider(
        'devstar.quickAccess',
        new QuickAccessTreeProvider()
      )
    );

    this.registerGlobalCommands(context);

    this.startDevStarHome();
  }


  async startDevStarHome() {
    vscode.commands.executeCommand('devstar.showHome');
  }


  registerGlobalCommands(context: vscode.ExtensionContext) {
    context.subscriptions.push(
      vscode.commands.registerCommand('devstar.showHome', (url: string) =>
        this.dsHome.toggle(url)
      ),
      vscode.commands.registerCommand('devstar.clean', () => {
        // 先清除ssh key
        if (fs.existsSync(this.user.getUserPrivateKeyPath())) {
          fs.unlinkSync(this.user.getUserPrivateKeyPath())
        }

        if (fs.existsSync(this.user.getUserPublicKeyPath())) {
          fs.unlinkSync(this.user.getUserPublicKeyPath())
        }
        console.log("User's ssh key has been deleted!")
        // 更新local user private key path
        this.user.updateLocalUserPrivateKeyPath("")
        // 退出登录
        this.user.logout()
      })
    );
  }
}

export function activate(context: vscode.ExtensionContext) {
  return new DevStarExtension(context);
}

export function deactivate() {
}
